#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    if(OpenDatabase()) {
        qDebug() << "连接SqlServer数据库成功！！！";
    }
    else {
        qDebug() << "连接SqlServer数据库失败！！！";
    }
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_pushButton_clicked()
{
    QSqlQueryModel *model = new QSqlQueryModel;
    model->setQuery(QObject::tr("select * from Area"));
    ui->tableView->setModel(model);
}

/*连接数据库*/
bool MainWindow::OpenDatabase()
{
    QSqlDatabase db = QSqlDatabase::addDatabase("QODBC");
    db.setDatabaseName(QString("DRIVER={SQL SERVER};"
                               "SERVER=%1;"
                               "DATABASE=%2;"
                               "UID=%3;"
                               "PWD=%4;").arg("127.0.0.1")
                       .arg("xingcun-BMPS")
                       .arg("sa")
                       .arg("123"));
    if (!db.open()) {
        QMessageBox::warning(0, qApp->tr("Cannot open database"),
                db.lastError().databaseText(), QMessageBox::Cancel);
        return false;
    }
    else {
        qDebug()<<"Connect to Database Success!";
        return true;
    }
}
